package com.zuijiajiao.servlab.databaseWEB.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.zuijiajiao.servlab.databaseWEB.DAOImpl.UserDaoImpl;
import com.zuijiajiao.servlab.databaseWEB.DTO.User;

@WebServlet({"/LoginServlet","/login.action"})
public class LoginServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	//private final long serialVersionUID=1L;
	public LoginServlet() {
		super();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		StringBuffer sb=req.getRequestURL();
		int start=sb.lastIndexOf("/");
		String str=sb.substring(start, sb.length());
		System.out.println("url:"+str);
		User user= null;
		UserDaoImpl dao= new UserDaoImpl();
		try{
			user = dao.findByNameAndPassword(name, password);
			if(user!=null){
				System.out.println(user);
				
				HttpSession session = req.getSession();
				session.setAttribute("user", user);
				/*session.setAttribute("name", name);
				session.setAttribute("password", password)*/;
				System.out.println(session);
				RequestDispatcher rq=req.getRequestDispatcher("/Welcome.jsp");
				rq.forward(req, resp);	
					
				req.getRequestDispatcher("/Welcome.jsp").forward(req, resp);
			}else{
				System.out.println("该用户不存在，请重新输入");
				resp.sendRedirect("index.jsp");
			}
			
		}catch(ClassNotFoundException ex){
			ex.printStackTrace();
		}
	}
}
